<template>
  <el-dialog :title="title"
             :visible.sync="visible"
             v-loading="loading"
             :before-close="modalClose"
             :close-on-click-modal="false"
             :close-on-press-escape="false"
             width="80%">
    <el-form ref="formRef"
             :model="formModel"
             :rules="formRules"
             label-width="140px">
      <el-form-item label="总店名称："
                    prop="companyId">
        <el-select v-model="formModel.companyId"
                   placeholder="请选择总店名称"
                   filterable
                   remote
                   reserve-keyword
                   clearable
                   :remote-method="(query) => {remoteMethod(query, 'headOffice')}"
                   :loading="loading1"
                   class="w-200"
                   @change="val=>handleSelect(val, 'headOffice')">
          <el-option v-for="item in headOfficeFilterList"
                     :key="item.id"
                     :label="item.name"
                     :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="参与分店：">
        <el-table :data="tableBranch"
                  border
                  style="width: 100%"
                  @selection-change="handleSelectionChange"
                  ref="asTable"
                  height="460">
          <el-table-column width="50"
                           type="selection"
                           fixed="left">
          </el-table-column>
          <el-table-column prop="id"
                           label="ID">
          </el-table-column>
          <el-table-column prop="hospitalId"
                           label="医院ID">
          </el-table-column>
          <el-table-column prop="hospitalName"
                           label="分店名字">
          </el-table-column>
          <el-table-column prop="manager"
                           label="店长">
          </el-table-column>
          <el-table-column prop="phone"
                           label="联系方式">
          </el-table-column>
        </el-table>
        <p align="left"
           class="mt-20">
          <!-- 已选：{{ allMultipleSelection }} -->
          <el-pagination background
                         @current-change="handleCurrentChange"
                         :current-page.sync="pagination.pageIndex"
                         :page-size="pagination.pageSize"
                         layout="total, prev, pager, next, jumper"
                         :total="pagination.totalNum">
          </el-pagination>
        </p>
      </el-form-item>
      <el-form-item label="指标解读医生：">
        <el-select v-model="formModel.doctorIds"
                   placeholder="请选择指标解读医生"
                   filterable
                   remote
                   reserve-keyword
                   clearable
                   :remote-method="(query) => {remoteMethod(query, 'doctor')}"
                   :loading="loading1"
                   class="w-200"
                   @change="val=>handleSelect(val, 'doctor')">
          <el-option v-for="item in doctorFilterList"
                     :key="item.id"
                     :value-key="item.id"
                     :label="item.nickName"
                     :value="item.id">
            <div class="doctor-list">
              <span>{{ item.nickName }}</span>
              <span>{{ item.loginName }}</span>
              <span>{{ item.hospitalName }}</span>
            </div>

          </el-option>
        </el-select>
        <el-button type="primary"
                   @click="handleAddItem(formModel.doctorIds)">添 加</el-button>
      </el-form-item>
      <el-form-item label="已选指标解读医生：">
        <el-table :data="tableData"
                  style="width: 100%"
                  border>
          <el-table-column prop="nickName"
                           label="医生姓名">
          </el-table-column>
          <el-table-column prop="loginName"
                           label="账号">
          </el-table-column>
          <el-table-column prop="hospitalName"
                           label="执业医院">
          </el-table-column>
          <el-table-column prop="departmentName"
                           label="所在科室">
          </el-table-column>
          <el-table-column prop="option"
                           label="操作">
            <template slot-scope="scope">
              <el-button type="danger"
                         @click="delRow(tableData, scope.$index)">删 除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
    </el-form>
    <p align="center">
      <el-button @click="modalClose"
                 type="primary">取 消</el-button>
      <el-button @click="submitForm"
                 type="primary">保 存</el-button>
    </p>
  </el-dialog>

</template>
<script>
  export default {
    props: {
      dataObj: {
        type: Object,
        default: {}
      },
      visible: {
        type: Boolean,
        default: false
      },
    },
    name: 'indicatorDialog', // 指标解读医生配置
    data () {
      return {
        title: '新 增',
        loading: false,
        loading1: false,
        loading2: false,
        formModel: {
          id: null,
          companyId: '',
          hospitalIds: '',
          doctorIds: '',
        },
        formRules: {
          companyId: [{ required: true, message: '请选择总店名称', trigger: 'chagne' }]
        },
        tableData: [],
        pageIndex: 1,
        pageSize: 10,
        headOfficeList: [],
        headOfficeFilterList: [],
        doctorList: [],
        doctorFilterList: [],
        multipleSelection: [],
        allMultipleSelection: [],
        pagination: {
          pageIndex: 1,
          pageSize: 10
        },
        tableBranch: []
      }
    },
    methods: {
      modalClose () {
        this.$emit('update:visible', false); // 直接修改父组件的属性
      },

      // 远程搜索
      remoteMethod (query, type) {
        if (query !== '') {
          let _this = this;
          if (query) {
            if (type === 'headOffice') { // 参与活动客户
              _this.loading1 = true;
              this.post(this.api.company.companyList, {
                pageIndex: this.pageIndex - 1,
                pageSize: this.pageSize,
                name: query,
                hospitalType: '',
                status: 1
              }).then(res => {
                if (res.data.code === '200') {
                  _this.loading1 = false;
                  _this.headOfficeList = res.data.object;
                }
              })
              setTimeout(() => {
                _this.loading1 = false;
                _this.headOfficeFilterList = _this.headOfficeList.filter(item => item.name.indexOf(query) > -1);

              }, 200)
            }
            if (type === 'doctor') { // 指标解读医生
              _this.loading2 = true;
              this.post(this.api.company.getReadDoctors, {
                searchCondition: query
              }).then(res => {
                if (res.data.code === '200') {
                  _this.loading2 = false;
                  _this.doctorList = res.data.object;
                }
              })
              setTimeout(() => {
                _this.loading2 = false;
                _this.doctorFilterList = _this.doctorList.filter(item => item.nickName.indexOf(query) > -1);
              }, 200)
            }
          }
        } else {
          if (type === 'headOffice') {
            this.activeCustomersFilterList = [];
          }
          if (type === 'doctor') {
            this.doctorFilterList = [];
          }

        }
      },
      handleSelect (item, type) {
        if (type === 'headOffice') {
          this.formModel.companyId = item;
          this.allMultipleSelection = [];
          this.fetchData();
        }
        if (type === 'doctor') {
          this.formModel.doctorIds = item;

        }
      },
      // 查询分店
      fetchData () {
        this.post(this.api.company.hospitalList, {
          pageIndex: this.pagination.pageIndex - 1,
          pageSize: this.pagination.pageSize,
          searchCondition: '',
          companyId: this.formModel.companyId
        }).then(res => {
          if (res.data.code === '200') {
            setTimeout(_ => {
              this.tableBranch = res.data.object;
              this.pagination.totalNum = res.data.totalNum;
              if (this.tableBranch.length === 0) {
                this.$message.error('该总店下面未查询到分店,请选择其它总店!');
                this.formModel.companyId = '';
                return
              }
              // 实现分页复选
              setTimeout(_ => {
                this.setSelectedRow();
              }, 50)
            }, 200)
          }
        })
      },
      setSelectedRow () {
        // 设置当前页已选项
        this.tableBranch.forEach(item => {
          if (this.allMultipleSelection.includes(item.hospitalId)) {
            this.$refs.asTable.toggleRowSelection(item, true);
            // console.log(item.id, 'set');
          }
        })
      },
      handleCurrentChange (val) {
        this.pagination.pageIndex = val;
        this.fetchData();
      },

      handleSelectionChange (val) {
        this.multipleSelection = val;
        // 实现分页复选
        setTimeout(_ => {
          this.resolveAllSelection();
        }, 50);
      },
      resolveAllSelection () {
        let currentPageData = this.tableBranch.map(item => item.hospitalId); // 当前页所有数据
        let currentPageSelected = this.multipleSelection.map(item => item.hospitalId); // 当前页已选数据
        let currentPageNotSelected = currentPageData.filter(item => !currentPageSelected.includes(item)); // 当前页未选数据
        // 将当前页已选数据放入所有已选项
        currentPageSelected.forEach(item => {
          if (!this.allMultipleSelection.includes(item)) {
            this.allMultipleSelection.push(item);
          }
        })
        // 将所有已选项数据中当前页没选择的项移除
        currentPageNotSelected.forEach(item => {
          let idx = this.allMultipleSelection.indexOf(item);
          if (idx > -1) {
            this.allMultipleSelection.splice(idx, 1);
          }
        })
      },
      delRow (table, index) {
        table.splice(index, 1);
      },
      handleAddItem (val) {
        if (this.tableData.some(item => item.id === val)) {
          this.$message.warning('不能重复添加指标解读医生!');
          this.formModel.doctorIds = '';
          return
        }
        let obj = this.doctorList.find(item => item.id === val);
        this.formModel.doctorIds = '';
        this.tableData.push(obj);
      },
      // 提交
      submitForm () {
        this.$refs['formRef'].validate((valid) => {
          if (valid) {
            if (this.multipleSelection.length === 0) {
              this.$message.error('至少勾选一家参与分店!');
              return
            }
            if (this.tableData.length === 0) {
              this.$message.error('至少添加一位指标解读医生!');
              return
            }
            let doctorIds = this.tableData.map(item => item.id);
            let { id, companyId } = this.formModel;
            let params = {
              id: id,
              companyId: companyId,
              doctorIds: JSON.stringify(doctorIds),
              hospitalIds: JSON.stringify(this.allMultipleSelection)
            }
            this.post(this.api.company.updateReadDoctorConfig, params).then(res => {
              if (res.data.code === '200') {
                this.$message.success('保存成功!');
                this.$parent.getList();
                this.modalClose();
              }
            })
          }
        })
      },
      getDetail () {
        this.post(this.api.company.getReadDoctorConfigDetail, {
          id: this.dataObj.id
        }).then(res => {
          if (res.data.code === '200') {
            let resData = res.data.object;
            this.formModel.id = resData.id;
            // 查询总店
            let { companyId, companyName } = resData;
            this.formModel.companyId = companyId;
            this.headOfficeFilterList = [
              { id: companyId, name: companyName }
            ];
            this.handleSelect(resData.companyId, 'headOffice'); // 回显分店
            this.allMultipleSelection = JSON.parse(resData.hospitalIds); // 回显选中的分店
            this.tableData = resData.doctorDtos;
          }
        })
      }
    },
    created () {
      if (this.dataObj) {
        this.getDetail();
        this.title = '编 辑';
      }
    },
  }
</script>
<style lang="scss" scoped>
  .doctor-list {
    display: flex;
    justify-content: space-between;
    span {
      padding-right: 20px;
    }
  }
</style>